# -*- coding: utf-8 -*-
#
# QCurrency Copyright (C) 2009  Chris Marsh
#
# Currency Converter is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or any later version.
#
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# *********************************************************************************
#
# converter.py, This module abstract the conversion data. Loads and provides
# the data to the gui module.
#
# *********************************************************************************

import os,  urllib2,  datetime
import converter_rc
from PyQt4.QtCore import QThread,  QObject,  QFile,  QIODevice,  QTextStream,  SIGNAL,  QDir
from PyQt4.QtGui import QDesktopServices

# *********************************************************************************

class ConversionType:
    Currency = 0
    Length = 1
    Weight = 2

# *********************************************************************************
    
class Converter(QObject):
    
    def __init__(self,  conversionType = 0):
        super(Converter, self).__init__()
        
        self.__conversionType = None
        self.__currencyDate = None
        self.__dataFile = None
        self.conversionData = {}
        self.setConversionType(conversionType)
        
        if not QFile.exists(self.dataPath()):
            dir = QDir()
            dir.mkpath(self.dataPath())
            QFile.copy(":/currency.dta", self.dataPath()+os.sep+"currency.dta")
            QFile.setPermissions(self.dataPath()+os.sep+"currency.dta",  QFile.WriteOwner|QFile.ReadOwner|QFile.ReadOther|QFile.ReadGroup)
    
    def dataPath(self):
        return QDesktopServices.storageLocation(QDesktopServices.DataLocation)
    
    def currencyDate(self):
        return self.__currencyDate

    def conversionType(self):
        return self.__conversionType
    
    def setConversionType(self,  conversionType):
        if conversionType == self.__conversionType:
            return
        self.__conversionType = conversionType
        if conversionType == ConversionType.Currency:
            self.__dataFile = self.dataPath()+os.sep+"currency.dta"
        elif conversionType == ConversionType.Length:
            self.__dataFile = ":/length.dta"
        else:
            self.__dataFile = ":/weight.dta"
    
    def downloadCurrency(self):
        try:
            sourceFile = urllib2.urlopen("http://rss.timegenie.com/forex.txt")
            localFile = open(self.dataPath()+os.sep+'currency.dta', 'w')
            todayStr = datetime.date.today().strftime("#%d/%m/%y\n")
            localFile.write(todayStr)
            for line in sourceFile:
                localFile.write(line)
            localFile.close()
            sourceFile.close()
            self.emit(SIGNAL("downloadSuccess"))
            self.loadData()
        except urllib2.URLError,  e:
            print "Data update FAILED.\n%s" % e
            self.emit(SIGNAL("downloadFailure"))
    
    def sortedDictValues(self,  adict):
        keys = adict.keys()
        keys.sort()
        return map(adict.get, keys)

    def loadData(self):
        self.conversionData.clear()
        try:
            sourceFile = QFile(self.__dataFile)
            sourceFile.open(QIODevice.ReadOnly)
            sourceInput = QTextStream(sourceFile)
            while not sourceInput.atEnd():
                line = sourceInput.readLine()
                if line[0] == "#":
                    self.__currencyDate = line[1:9]
                else:
                    fields = line.split("|")
                    try:
                        value = (fields[1],  float(fields[2]))
                        self.conversionData[unicode(fields[0])] = value
                    except Exception,  e:
                        print e
            sourceFile.close()
            self.emit(SIGNAL("dataLoaded"))
        except Exception, e: 
            print e
    
    def convert(self,  value,  idFrom,  idTo):
        return  (self.conversionData[idTo][1]/self.conversionData[idFrom][1]) * value

# *********************************************************************************
